package com.api.demo.service.impl;

import com.api.demo.entity.Content;
import com.api.demo.entity.ContentLike;
import com.api.demo.mapper.ContentLikeMapper;
import com.api.demo.mapper.ContentMapper;
import com.api.demo.service.ContentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class ContentServiceImpl extends ServiceImpl<ContentMapper, Content> implements ContentService {

    @Autowired
    private ContentLikeMapper contentLikeMapper;

    @Autowired
    private ContentMapper contentMapper;

    @Override
    public Content createContent(Content content) {
        content.setCreateTime(LocalDateTime.now());
        content.setUpdateTime(LocalDateTime.now());
        content.setLikeCount(0);
        content.setCommentCount(0);
        save(content);
        return content;
    }

    @Override
    public Content updateContent(Content content) {
        Content existingContent = getById(content.getId());
        if (existingContent == null) {
            throw new IllegalArgumentException("内容不存在");
        }
        if (!existingContent.getUserId().equals(content.getUserId())) {
            throw new IllegalArgumentException("无权修改该内容");
        }

        content.setUpdateTime(LocalDateTime.now());
        // 保持原有的不可修改字段不变
        content.setCreateTime(existingContent.getCreateTime());
        content.setLikeCount(existingContent.getLikeCount());
        content.setCommentCount(existingContent.getCommentCount());

        updateById(content);
        return content;
    }

    @Override
    public IPage<Content> getContentList(Page<Content> page) {
        QueryWrapper<Content> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1); // 只查询已发布的内容
        queryWrapper.orderByDesc("create_time");
        return page(page, queryWrapper);
    }

    @Override
    public IPage<Content> getMyContentList(Page<Content> page, Long userId, Integer status) {
        QueryWrapper<Content> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        queryWrapper.orderByDesc("create_time");
        return page(page, queryWrapper);
    }

    @Override
    public Content getContentDetail(Long id) {
        Content content = getById(id);
        if (content == null || content.getStatus() == 2) { // 2表示已删除
            throw new IllegalArgumentException("内容不存在");
        }
        return content;
    }

    @Override
    public void deleteContent(Long id, Long userId) {
        Content content = getById(id);
        if (content == null) {
            throw new IllegalArgumentException("内容不存在");
        }
        if (!content.getUserId().equals(userId)) {
            throw new IllegalArgumentException("无权删除该内容");
        }
        contentMapper.deleteById(content.getId());
    }

    @Override
    @Transactional
    public void likeContent(Long contentId, Long userId) {
        // 检查内容是否存在
        Content content = getById(contentId);
        if (content == null || content.getStatus() == 2) {
            throw new IllegalArgumentException("内容不存在");
        }

        // 检查是否已经点赞
        QueryWrapper<ContentLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("content_id", contentId)
                .eq("user_id", userId);
        if (contentLikeMapper.selectCount(queryWrapper) > 0) {
            return; // 已经点赞过了，直接返回
        }

        // 创建点赞记录
        ContentLike contentLike = new ContentLike();
        contentLike.setContentId(contentId);
        contentLike.setUserId(userId);
        contentLike.setCreateTime(LocalDateTime.now());
        contentLikeMapper.insert(contentLike);

        // 更新内容的点赞数
        content.setLikeCount(content.getLikeCount() + 1);
        updateById(content);
    }

    @Override
    @Transactional
    public void unlikeContent(Long contentId, Long userId) {
        // 检查内容是否存在
        Content content = getById(contentId);
        if (content == null || content.getStatus() == 2) {
            throw new IllegalArgumentException("内容不存在");
        }

        // 删除点赞记录
        QueryWrapper<ContentLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("content_id", contentId)
                .eq("user_id", userId);
        if (contentLikeMapper.delete(queryWrapper) > 0) {
            // 只有成功删除点赞记录时才减少点赞数
            content.setLikeCount(content.getLikeCount() - 1);
            updateById(content);
        }
    }

    @Override
    public IPage<Content> searchContent(String keyword, Integer type, Integer status, Page<Content> page) {
        QueryWrapper<Content> queryWrapper = new QueryWrapper<>();

        // 默认只搜索已发布的内容
        if (status != null) {
            queryWrapper.eq("status", status);
        } else {
            queryWrapper.eq("status", 1);
        }

        // 按内容类型筛选
        if (type != null) {
            queryWrapper.eq("type", type);
        }

        // 模糊搜索标题、描述和内容
        queryWrapper.and(wrapper -> wrapper
                .like("title", keyword)
                .or()
                .like("description", keyword)
                .or()
                .like("content", keyword));

        // 按创建时间倒序排序
        queryWrapper.orderByDesc("create_time");

        return page(page, queryWrapper);
    }

    @Override
    public IPage<Content> homeContent(Page<Content> page, Long userId) {
        QueryWrapper<Content> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)
        .eq("user_id", userId)
        .orderByDesc("create_time");
        return page(page, queryWrapper);
    
    }
}